import React, { Component,useEffect,useRef,useState} from 'react'
import "./index.scss"
import {reg} from "../../utils/validate"
import {Tabs ,Form,Checkbox,Button,Input,Space,message } from "antd"
import { UserOutlined,LockOutlined ,MobileOutlined} from '@ant-design/icons';
import { request } from '../../api';
import MobxData from "../../mobx/data"
const { TabPane } = Tabs;
const {phone,pwd}  = reg;
export default class LoginCom extends Component {
    render() {
        return (
            <div>
                <div className="loginBox">
                    <Tabs defaultActiveKey="1" >
                        <TabPane tab="密码登录" key="1">
                            <LoginByPassword history={this.props.history}></LoginByPassword>
                        </TabPane>
                        <TabPane tab="手机号登录" key="2">
                            <LoginByMessage history={this.props.history}></LoginByMessage>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        )
    }
}
const layout = {
    labelCol: { offset:2,span: 0 },
    wrapperCol: { offset:0, span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 4, span: 16 },
  };
function LoginByPassword ({history}){
    const myForm = useRef()
    const onFinish=(value)=>{
        // console.log(value);
        
        request.login(value)
        .then(res=>{
            if(res.code==200){
                console.log(res.result);
                history.push("/main")
                localStorage.setItem("userinfo",JSON.stringify(res.result))
                localStorage.setItem("token",res.token)
                localStorage.setItem("isAutoLogin",value.remember)
            }
        })
    }
    const onFinishFailed=()=>{
        message.error("请输入有效登录信息")
    }
    useEffect(()=>{
        if(localStorage.isAutoLogin=="true"){
            var userinfo = JSON.parse(localStorage.getItem("userinfo"))
            myForm.current.setFieldsValue({...userinfo,remember:true})
        }else{
            if(JSON.parse(localStorage.getItem("userinfo"))!=null){
                var phone = JSON.parse(localStorage.getItem("userinfo")).phone
                myForm.current.setFieldsValue({phone:phone})
            }
        }
    },[])
    return(
        <div>
            <Form
                {...layout}
                name="basic"
                initialValues={{}}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                ref={myForm}
                >
                <Form.Item
                    label="电话"
                    name="phone"
                    rules={[{ required: true, message: 'Please input your phone!' },{
                        pattern:phone,message:'请输入正确格式的手机号码'
                    }]}
                >
                    <Input size="large" prefix={<UserOutlined />}/>
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: 'Please input your password!' },{
                        pattern:pwd,message:'6-16位数字加字母'
                    }]}
                >
                    <Input.Password size="large" prefix={<LockOutlined />}/>
                </Form.Item>

                <Form.Item {...tailLayout} name="remember" valuePropName="checked">
                    <Checkbox>记住密码</Checkbox>
                </Form.Item>

                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit" size="large" shape="round" block>
                    登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}



const { Search } = Input;
var timer=null;
function LoginByMessage ({history}){
    const myForm = useRef()
    const [flag,setFlag] = useState(true)
    let [count,setCount] = useState(30)
    const onFinish=(value)=>{
        console.log(value);
        request.getcaptcha(value)
        .then(res=>{
            if(res.code==200){
                history.push("/main")
                localStorage.setItem("token",res.token)
                localStorage.setItem("userinfo",JSON.stringify(res.data)) 
                // MobxData.changeuserinfo(res.result) 
            }
        })
    }
    const onFinishFailed=()=>{
        message.error("请输入有效登录信息")
    }
    const onSearch=()=>{
        var phone = myForm.current.getFieldValue('phone')
        const phoneCaptcha =reg.phone.test(phone)
        if(phoneCaptcha!=false){
            setFlag(false)
            timer = setInterval(() => {
                // setCount(count)
                if(count>0){
                    setCount(--count)
                    setFlag(false)
                }else{
                    clearInterval(timer)
                    timer = null
                    setCount(30)
                    setFlag(true)
                }
            }, 1000);
            sendCaptch()
        }
    }
    const sendCaptch=()=>{
        var phone = myForm.current.getFieldValue('phone')
            request.sendcaptcha({phone:phone})
            .then(res=>{
    
            })
    }
    useEffect(()=>{
        var userinfo = JSON.parse(localStorage.getItem("userinfo"))
        if(userinfo){
            console.log(myForm);
            myForm.current.setFieldsValue({phone:userinfo.phone})
        }
    },[])
    return(
        <div>
            <Form
                {...layout}
                name="basic"
                initialValues={{}}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                ref={myForm}
                className="loginForm"
                >
                <Form.Item
                    label="手机号"
                    name="phone"
                    rules={[{ required: true, message: 'Please input your phone!' },{
                        pattern:phone,message:'请输入正确格式的手机号码'
                    }]}
                >
                    <Input size="large" prefix={<MobileOutlined />}/>
                </Form.Item>

                <Form.Item
                    label="验证码"
                    name="captcha"
                    rules={[{ required: true, message: 'Please input your Verification!' }]}
                >
                    {   
                        <Search
                        placeholder="set your Verification"
                        allowClear
                        enterButton={flag?"验证码发送":count+" S"}
                        size="large"
                        onSearch={onSearch}
                        maxLength="4"
                        />
                    }
                </Form.Item>
                

                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit" size="large" shape="round" block>
                    登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}